package com.zhangyue.wqercs.recyclerviewdemo;

import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.graphics.ColorUtils;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder>
        implements OnItemChangeListener{

    private final List<String> list;

    public MyRecyclerAdapter(List<String> list){
        this.list = list;
    }

    //该方法将会创建viewholder来复用控件。跟listview中viewholder同理
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        //获取item的view视图，这里采用的是系统提供的视图。
        View view = LayoutInflater.from(viewGroup.getContext()).
                inflate(android.R.layout.simple_list_item_1,viewGroup,false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }
    //给viewholder中的控件赋值
    //param1 viewholder对象。通过它可以拿到复用控件
    //param2 i就是position。可以拿到第几个item的下标
    @Override
    public void onBindViewHolder(@NonNull final MyViewHolder myViewHolder, final int i) {
        myViewHolder.tv.setText(list.get(i));
        //给每个item添加点击事件
        myViewHolder.tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //使用SnackBar进行提示。SnackBar可以理解为可交互的Toast。是谷歌MD推出的新提示控件
                Snackbar.make(myViewHolder.tv,"item:"+i,Snackbar.LENGTH_LONG).show();
            }
        });
    }

    //当拖拽动画完成之后调用该方法。需要修改list拖拽之后的数据
    @Override
    public void change(int from, int to) {
        //交换list的数据  将from和to进行交换
        Collections.swap(list,from,to);
        //更新item移动之后的2个数据
        notifyItemMoved(from,to);
    }


    //创建一个viewholder来保存itemview的数据
    class MyViewHolder extends RecyclerView.ViewHolder{
        public TextView tv;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
            layoutParams.height = (int)(Math.random()*150+50);
            itemView.setBackgroundColor(
                    Color.rgb((int) (Math.random()*255),
                            (int) (Math.random()*255),(int)(Math.random()*255)));
            //将textview赋值给tv
            this.tv = itemView.findViewById(android.R.id.text1);
        }
    }

    //需要创建的item数，与listview的getCount一样
    @Override
    public int getItemCount() {
        return list.size();
    }
}
